import json
import os.path
import time

from fastapi import FastAPI ,WebSocket , Request
from  apilib.component import compManager , TComp

class TCompWs ( TComp):
    def __init__(self):
        super().__init__()
        self.sessions = {}
        self.handlers={
            "getSessions" : self.getSessions,
            "sendMsg":self.sendMsg
        }
        self.asyncHandlerKeys=['sendMsg']
        self.enableClientIps=[]
        self.autoStartServices = [
            self.load
        ]
    async def sendMsg(self , msg ):
        try:
            recList = [x['ws'] for x in self.sessions.values() if msg['ac'] in  x['subAcs']]
            for ws in  recList:
                try:
                    content = json.dumps(msg , ensure_ascii=False)
                    await  ws.send_text(content)
                except Exception as eer:
                    print('send msg error.' , eer)
                    self.manager.log(eer)
        except Exception as eer:
            self.manager.log(eer , self)
    async def notifySessions(self  ):
        try:
            msg ={
                "ac":"sessionChanged" ,
                "data": self.getSessions()
            }
            await  self.sendMsg(msg)
        except Exception as eer:
            self.manager.log(eer , self)
    async def acceptWs(self , websocket:WebSocket ):
        try:
            print('wsInfo' , websocket.client.host)
            await websocket.accept()
            sessionId = str(websocket)[1:-1].split(' ')[-1]
            while True:
                try:
                    time.sleep(0.01)
                    recData = await websocket.receive_text()
                    msgFlag , msg = self.isMsg(recData)
                    if msgFlag :
                        try:
                            if ( msg['data']['msgType']!='RunningTime'):
                                print('ws rec msg:', msg)
                        except Exception as errMsg:
                            pass

                        if msg['ac'] =='regist':
                            self.sessions[sessionId] ={
                                "sessionId": sessionId ,
                                "registTime": time.time(),
                                "peerId": msg['data']['peerId'],
                                "peerType": msg['data']['peerType'],
                                "subAcs": msg['data']['subAcs'],
                                'tag': msg['data']['tag'] if 'tag' in msg['data'].keys() else {},
                                'peerIp': websocket.client.host,
                                "ws": websocket
                            }
                            await self.notifySessions()
                        else:
                            try:
                                await  self.sendMsg(msg)
                            except Exception as eeSender:
                                self.manager.log(eeSender)
                except Exception as eer:
                    print('rec msg error;',recData , eer);
                    self.manager.log(eer)
                    break
            if sessionId in self.sessions.keys():
                del self.sessions[sessionId]
            await self.notifySessions()
        except Exception as eer:
            self.manager.log(eer , self)
    def getSessions(self ):
        res = []
        try:
             res = [
                 {
                     "sessionId": x['sessionId'],
                     "registTime": x['registTime'],
                     "peerId": x['peerId'],
                     "peerType": x['peerType'],
                     "peerIp": x['peerIp'],
                     "tag": x['tag']
                 }
                 for x in self.sessions.values()
             ]
        except Exception as eer:
            self.manager.log(eer , self)
        return  res
    def load(self):
        try:
            pass
        except Exception as er:
            self.manager.log(er)

    def isMsg(self , msgStr):
        res = False
        msg ={}
        try:
            msg = json.loads(msgStr)
            res = 'ac' in msg.keys() and 'data' in msg.keys()
        except Exception as er:
            self.manager.log(er)
        return  res , msg

_settings={
    "rootPath":"/"
}
compManager.registComponentType('TCompWs' , TCompWs , _settings)
print(compManager.components.keys())